import { Component, OnInit } from '@angular/core';
import {HomeService} from "../home.service";
import index from "@angular/cli/lib/cli";
import {LoadingService} from "../../../share/loading.service";
import {AlertService} from "../../../share/alert.service";

@Component({
  selector: 'app-home-list',
  templateUrl: './home-list.component.html',
  styleUrls: ['./home-list.component.scss']
})


export class HomeListComponent implements OnInit {
  public homeBanner:Array<any> = [];
  public backIamge:Array<any> = [];
  public imgUrl:string = IMG_URL;
  public homeTab:Array<any> = ['百年品牌',"准百年品牌"];
  public rankData:Array<any> = [];
  public rankData2:Array<any> = [];
  public select:number = 0;
  public selectYear:number = 1;
  public showTab:boolean = true;
  public noMoreRank:boolean = false;
  public noMoreRankList:boolean = false;
  //滚动请求数据
  public scrollData:boolean = false;
  //state : 1、网路人气榜，2、品牌价值榜，3、爱心公益榜，4、商业赞助榜，5、企业实力榜，6、与时俱进榜，7、幸福指数榜
  //type: 1、百年 2、准百年
  public params:object = {
    type:1,
    state:1
  };
  public params2:object = {
    type:1,
    state:1
  };
  public years:any;
  public title:string = '网络人气榜';
  public brandsLists:Array<any> = [];
  public rankDataList:Array<any> = [];
  public rankDataList2:Array<any> = [];
  public voteId:any;
  public aaa:boolean = false;
  public noMore:boolean = false;

  constructor(public service:HomeService,
              public loading:LoadingService,
              public alert:AlertService
              ) {

  }

  ngOnInit(): void {
    this.service.getData({}).subscribe(
      res => {
        console.log(res);
        if(res['code'] == 0){

        }else {
          this.service.saveData({}).subscribe(
            res => {
              console.log(res);
            }
          )
        }
      }
    );


    this.brandsLists = [];
    this.params['page'] = 1;
    //获取 上月末 排行榜
    this.params2['types'] = new Date().getMonth();
    this.getBannerData();
    if(document.body.clientWidth <= 600){
      this.getHomeImg(2);
    }else {
      this.getHomeImg(1);
    }
    this.getRankData(1);
    //获取季度排行
    this.getEnterprise();
    this.years = new Date().getFullYear();
    this.getEnterpriseYear(this.years);

    let swiper = new Swiper('.swiper-container',{
      //自动轮播
      autoplay:5000,
      //分页
      pagination : '.swiper-pagination',
      //滑动方向  水平滑动
      direction : 'horizontal',
      paginationClickable: true,
      longSwipesRatio: 0.3,
      touchRatio:1,
      //修改swiper自己或子元素时，自动初始化swiper
      observer:true,
      //修改swiper的父元素时，自动初始化swiper
      observeParents:true,
    });
    window.onscroll = () => {
      let height = document.documentElement;
      let scrollTopPx = document.documentElement.scrollTop || window.pageYOffset || document.body.scrollTop;
      if(height.scrollHeight - scrollTopPx - height.clientHeight <= height.scrollHeight * .2 && this.scrollData){
        this.scrollData = false;
        this.params['page']++;
        this.upLoadData();
      }
    }
  }
  //获取轮播数据
  getBannerData(){
    // 如果要const一个params
    const params = {
      type:1
    };
    //subscribe 是订阅  方法都写在这里面this.service.getBanner(params) 前面这一块都是获取数据 的一些不用管的请求 然后subscribe 是获取之后  的操作写在这里
    this.service.getBanner(params).subscribe(
      res => {
        if(res['code'] == 0){
          this.homeBanner = res['data'];
          if(this.homeBanner){
            this.homeBanner.map((v) => {
              v['image_url'] = JSON.parse(v['image_url'])[0]
            });
          }
        }
      }
    );
  }

  tabClick(index){
    this.params['page'] = 1;
    this.params['type'] = index + 1;
    this.select = index;
    if(index == 0){
      this.showTab = true;
    }else {
      this.showTab = false;
    }
    this.getRankData(this.params['state']);
    this.getEnterprise();
    this.getEnterpriseYear(this.years);
  }
  //获取背景图
  getHomeImg(tmp){
    const params = {
      type:tmp
    };
    this.service.getBackImage(params).subscribe(
      res =>{
        if(res['code'] == 0){
          this.backIamge = res['data'];
          if(this.backIamge){
              this.backIamge.map((v) => {
                v['img'] = IMG_URL + JSON.parse(v['img'])[0];
              })
          }
        }
      }
    )
  }
  //获取排行数据
  getRankData(state,name?){
    this.params['page'] = 1;
    this.loading.show();
    if(name){
      this.title = name;
    }
    this.params['state'] = state;
    this.service.getRank(this.params).subscribe((res) => {
      if(res['code'] == 0){
        if(res['data'] && res['data']['data'].length >= 10){
          this.scrollData = true;
        }else {
          this.scrollData = false;
        }
        res['data']['data'].map((v) => {
          v['logo'] = IMG_URL + JSON.parse(v['logo'])[0];
        });
        this.brandsLists = res['data']['data'];
        // this.backupRank = this.brandsLists;

        this.loading.hide();
      }
    })
  }
  upLoadData(flag?,page?){
    let params2 = this.params;
    if(page){
      params2['page'] = page;
    }
    this.service.getRank(params2).subscribe((res) => {
      if(res['code'] == 0){
        if(!flag){
          if(res['data'] && res['data']['data'].length >= 10){
            this.scrollData = true;
          }else {
            this.noMore = true;
            this.scrollData = false;
          }
        }
        res['data']['data'].map((v) => {
          v['logo'] = IMG_URL + JSON.parse(v['logo'])[0];
        });
        this.brandsLists = this.brandsLists.concat(res['data']['data']);
        // this.backupRank = this.brandsLists;
        this.loading.hide();
      }
    })
  }
  //投票
  voteAdd(id){
    this.aaa = true;
    if(this.voteId == id){
      this.alert.show('每天只能投给同一公司一张票哦~');
    }else {
      const params = {
        id:id,
        ip:localStorage.ip
      };
      this.service.putVote(params).subscribe(
        res => {
          if(res['code'] == 0){
            this.voteId = id;
            this.alert.show('投票成功!');
            if(this.aaa && this.params['page'] > 1){
              this.scrollData = false;
              this.brandsLists = [];
              let page;
              let page2 = this.params['page'];
              for (let i = 1;i < page2+1;i++){
                setTimeout(() => {
                  page = i;
                  this.upLoadData(true,page);
                },200);
              }
            }else {
              this.getRankData(this.params['state']);
            }
          }else if(res['code'] == 3047){
            this.alert.show('每天只能投给同一公司一张票哦~');
          }else {
            this.alert.show(res['msg']);
          }
        }
      );
    }
  }
  //获取月榜单数据
  getEnterprise(){
    this.params2['type'] = this.params['type'];
    this.params2['state'] = this.params['state'];
    this.params2['years'] = 2018;
    this.service.getEnterpriseRank(this.params2).subscribe(
      res => {
        if(res['code'] == 0){
          this.rankData = res['data'];
          this.rankData2 = res['data'];
          if(this.rankData.length > 0){
            this.noMoreRankList = false;
          }
          if(this.rankData.length >= 10){
            this.rankData = this.rankData.slice(0,10);
          }else if(this.rankData.length == 0){
            this.noMoreRankList = true;
          }
        }
      }
    )
  }
  //获取历年数据
  getEnterpriseYear(year,index?){
    if(index){
      this.selectYear = index;
    }
    this.loading.show();
    const params = {
      types:4,
      type:this.params['type'],
      state:this.params['state'],
      years:year
    };
    this.service.getEnterpriseYearsRank(params).subscribe(
      res => {
        this.loading.hide();
        if(res['code'] == 0){
          this.rankDataList = res['data']['data'];
          this.rankDataList2 = res['data']['data'];
          if(this.rankDataList.length >= 10){
            this.rankDataList = this.rankDataList.slice(0,10);
          }
          if(this.rankDataList.length == 0){
            this.noMoreRank = true;
          }else {
            this.noMoreRank = false;
          }
        }
      }
    )
  }

}
